package com.rtc.agoracall

import android.app.Activity
import android.app.Application
import android.content.Context
import android.provider.Settings
import android.util.Log
import androidx.lifecycle.AndroidViewModel
import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.rtc.call.core.data.ConfigResponse
import com.rtc.call.core.data.request.ConfigRequest
import com.rtc.call.core.network.repository.ConfigRepository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.flow.collectLatest
import kotlinx.coroutines.launch
import org.json.JSONObject

/**
 * ViewModel for MainActivity
 */
class MainViewModel(context: Activity) : ViewModel() {
    
    // LiveData to track config loading state
    private val _configLoadingState = MutableLiveData<ConfigState>()
    val configLoadingState: LiveData<ConfigState> = _configLoadingState
    
    // LiveData for the config data
    private val _configData = MutableLiveData<ConfigResponse?>()
    val configData: LiveData<ConfigResponse?> = _configData
    private val repository = ConfigRepository(context)
    private val deviceId = getDeviceId(context);
    /**
     * Fetch configuration from the server
     */
    fun getConfig() {
        _configLoadingState.value = ConfigState.LOADING
        
        // Simulate network request in a coroutine
        viewModelScope.launch(Dispatchers.IO) {
            val request = ConfigRequest()
            request.status = "TURNON"
            request.devId = deviceId
            request.lastNfcId = ""
            request.nfcId = ""
            request.version = "TESTDEV_0.0.1"
            request.agoraRequest = "1"
            repository.getConfig(request).collectLatest { result ->
                if (result.isSuccess) {
                    _configData.postValue(result.getOrNull())
                    _configLoadingState.postValue(ConfigState.SUCCESS)
                } else{
                    _configLoadingState.postValue(ConfigState.ERROR)
                }

            }

        }
    }
    

    
    /**
     * Reset the ViewModel state
     */
    fun reset() {
        _configLoadingState.value = ConfigState.IDLE
        _configData.value = null
    }
    
    /**
     * Enum for configuration loading states
     */
    enum class ConfigState {
        IDLE,
        LOADING,
        SUCCESS,
        ERROR
    }

    private fun getDeviceId(context: Context): String {
        return "3351e12d926e62ca"
//        return Settings.Secure.getString(context.contentResolver, Settings.Secure.ANDROID_ID)
    }
} 